package com.arlen.centre.exceptionHandle;

import com.arlen.until.thread.WxMessageUuidThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@ControllerAdvice(basePackages = "com.arlen.general")
public class CaptureException {

    @Autowired
    RedisTemplate redisTemplate;

    @ExceptionHandler(WxException.class)
    public void captureExcept(HttpServletResponse response, WxException wxException, HttpServletRequest request) {
        response.setContentType("application/json;charset=utf-8");
        String message = wxException.getMessage();
        String uuid = WxMessageUuidThread.get();
        Map mesMap = (Map) redisTemplate.opsForValue().get(uuid);
        String requestMes = "<xml>\n" +
                "  <ToUserName><![CDATA[" + mesMap.get("FromUserName") + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + mesMap.get("ToUserName") + "]]></FromUserName>\n" +
                "  <CreateTime>" + System.currentTimeMillis() / 1000 + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + message + "]]></Content>\n" +
                "</xml>";
        try (PrintWriter writer = response.getWriter();) {
            writer.write(requestMes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}